package cs.third;

import java.util.concurrent.atomic.AtomicInteger;

class Coupon {
    private final AtomicInteger remaining;

    public Coupon(int total) {
        this.remaining = new AtomicInteger(total);
    }

    // 尝试抢购优惠券（原子操作）
    public boolean trySeize() {
        while (true) {
            int current = remaining.get();
            if (current <= 0) return false;
            // 使用CAS操作保证原子性
            if (remaining.compareAndSet(current, current - 1)) {
                return true;
            }
        }
    }

    public int getRemaining() {
        return remaining.get();
    }
}

